package com.haohuo.interceptor;

import com.haohuo.config.constans.TraceConstans;
import com.haohuo.util.TraceIDUtil;
import org.slf4j.MDC;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * resttemplate请求客户端设置trace信息
 *
 * @Author: pk.zhang
 * @Date: 2021/3/10 10:26
 */
@Component
public class RestTraceInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders headers = request.getHeaders();
        String traceId = MDC.get(TraceConstans.TRACEID_KEY);
        if (StringUtils.isEmpty(traceId)) {
            traceId = String.valueOf(TraceIDUtil.incrementAndGet());
        }
        // 请求头传递参数:trace-id
        headers.add(TraceConstans.TRACEID_KEY, traceId);
        // 保证请求继续被执行
        return execution.execute(request, body);
    }
}
